package com.jinzhi.jzapi.controller;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.itextpdf.text.pdf.security.CertificateUtil;
import com.jinzhi.common.type.ApiEnumError;
import com.jinzhi.common.utils.*;
import com.jinzhi.jzapi.domain.UserDO;
import com.jinzhi.jzapi.service.UserService;
import com.jinzhi.jzapi.utils.JWTUtil;
import com.jinzhi.jzapi.utils.RedisUtil;
import com.jinzhi.jzapi.vo.LoginVo;
import com.jinzhi.jzapi.vo.SendSmsVo;
import com.jinzhi.jzweb.domain.MessageplatfromDO;
import com.jinzhi.jzweb.service.MessageplatfromService;
import com.jinzhi.sys.vo.UserVO;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/jinZhiIndex/userServer")
public class UserServiceController {

    @Autowired
    private UserService userService;
    @Resource
    private RedisUtil redisUtil;
    @Autowired
    private MessageplatfromService messageplatfromService;




    /**
     * 用于获取信息
     * @param token
     * @return
     */
    @PostMapping("getUserInfo")
    public Object getMemberInfo(String token) {
        if(StringUtils.isBlank(token)){

            return ApiResult.fail("未登录！");
        }
        //调用jwt工具类的方法，根据request对象获取头信息，返回对象id
//        if(redisUtil.get(token)==null){
//            return ApiResult.fail("用户不存在");
//        }
        // String userid=  redisUtil.get(token).toString();;
        //查询数据库根据用户id获取用户数据
        UserDO member = userService.selectById(JWTUtil.getUser().getId());

        if(member==null){
            return ApiResult.fail("用户不存在");
        }

        return ApiResult.success(member);

    }


    /**
     * 判断token是否过期
     * @param token
     * @return
     */
    @GetMapping("/isToken")
    public ApiResult<?> isToken(String token) {
        boolean tokenExpired = JWTUtil.isTokenExpired(token);
        return ApiResult.success(tokenExpired);
    }




    @PostMapping("/loginNu")
    ApiResult<?> ajaxLogin(String username, String password, HttpServletRequest req) {

        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
            UserDO userDO = (UserDO) subject.getPrincipals().getPrimaryPrincipal();
            //根据手机号码生成自定义登录态
            String returnToken = userService.getToken(  userDO.getMobile());
            //将生成的登录态和手机号码关联，并存到缓存中
            Map cache = new HashMap();
            cache.put("mobile", userDO.getMobile());
           // EhCacheUtil.put(returnToken.getToken(), cache);
            //返回登录态和用户信息
            Map<String, Object> map = new HashMap<>();
            map.put("token", returnToken);
            map.put("userName", userDO.getUsername());
            map.put("type", userDO.getType());
            map.put("uName", userDO.getName());
            req.getSession().setAttribute("userName", userDO.getUsername());
            return ApiResult.success(map);
        } catch (AuthenticationException e) {
            return ApiResult.fail("登录错误！");
        }
    }


    @PostMapping("/loginPass")
    Object ajaxLogin(String username, String password) {
        String pass=  MD5Utils.convertMD5(password);
        UsernamePasswordToken token = new UsernamePasswordToken(username, pass);
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
        } catch (AuthenticationException e) {
            return ApiResult.fail();
        }
        return ApiResult.success();
    }

    /**
     * wxid =103 其他跟金职母婴保持一致
     * @param loginVo
     * @return
     */
    @PostMapping("/login")
    public Object login( LoginVo loginVo){
        Map map =new HashMap();
        if(loginVo.getWxId()==null){
            return ApiResult.fail("参数为空！");
        }
        if(StringUtils.isBlank(loginVo.getCode())){
            return ApiResult.fail("参数为空！");
        }
        map.put("wxId",loginVo.getWxId());
        map.put("encryptedData",loginVo.getEncryptedData());
        map.put("iv",loginVo.getIv());
        map.put("code",loginVo.getCode());
        map.put("lnviteUserId",loginVo.getLnviteUserId());
        AtomicInteger atomicIntege=new AtomicInteger();
        atomicIntege.getAndIncrement();
        Object token=   userService.login(map);
        return ApiResult.success(token);
    }

    /**
     *
     退出登录接口
     */
    @PostMapping("/userSignOut")
    public ApiResult<?> userSignOut(String token) {
        redisUtil.del(token);
        return ApiResult.success();
    }

    /**
     *
     退出登录接口
     */
    @PostMapping("/testMobile")
    public ApiResult<?> testMobile(String mobile) {
        redisUtil.set(mobile+RedisUtil.code,"111",200);
        return ApiResult.success();
    }

    /**
     *
     退出登录接口
     */
    @PostMapping("/getMobileTime")
    public ApiResult<?> getMobileTime(SendSmsVo mobile) {

        System.out.println();
        return ApiResult.success(redisUtil.getExpire(mobile+RedisUtil.code));
    }



    /**
     *
     * @Param: [wxId, mobile]
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-06-20
     */
    @PostMapping("/sendLogin")
    // @ApiOperation(value = "api小程序端-发送注册验证短信", httpMethod = "POST")
    public ApiResult<?> mobileLogin(SendSmsVo sendSmsVo) {
        sendSmsVo.setAccount(sendSmsVo.getMobile());
        if (StringUtils.isBlank(sendSmsVo.getCode())) {
            return ApiResult.lack("code");
        } else {
            //第二步，判断验证码
            try {
                String rediskey=sendSmsVo.getMobile()+RedisUtil.code;
                String mobileCode= (String) redisUtil.get(rediskey);


                if(!mobileCode.equals(sendSmsVo.getCode())){
                    return ApiResult.fail("验证码错误");
                }
            } catch (Exception e) {
                return ApiResult.build(ApiEnumError.apiSmsCodeInvalid.getCode(), ApiEnumError.apiSmsCodeInvalid.getMsg());
            }
            //第三步，根据手机号码获取用户信息并判断，如没有则新建，如果则返回信息
            EntityWrapper<UserDO> wrapper=new EntityWrapper();
            wrapper.like("mobile",sendSmsVo.getAccount());
            List<UserDO> userDOS=userService.selectList(wrapper);
            UserDO userDO = new UserDO();
            if (userDOS.size()==0) {
                userDO.setUsername(sendSmsVo.getAccount());//默认手机号为新建账号的初始用户名
                userDO.setWxId(sendSmsVo.getWxId()); //微信id
                userDO.setMobile(sendSmsVo.getAccount());
                userDO.setOrderPhone(sendSmsVo.getAccount()); //接单手机号默认与登录手机号一致
                userDO.setCurrentPoints("0"); //当前积分默认0
                userDO.setAccumulatedPoints("0"); //累计积分默认也是0
                userDO.setTotalMoney("0"); //累计充值金额
                userDO.setNickname("新用户"+""+jmMobile(sendSmsVo.getAccount())); //昵称
                //设置默认密码
                String salt = UUIDUtils.get();
                String passwd = PasswdUtils.get(null, salt);
                userDO.setSalt(salt);
                userDO.setPassword(passwd);
                userDO.setType(0);//默认普通用户
                userDO.setGmtCreate(new Date());
                userDO.setGmtModified(userDO.getGmtCreate());
                userDO.setStatus(1);//默认正常
                userDO.setSex(0L);//默认未知
                List<Long> list = new ArrayList<>();
                list.add(56L);
              boolean b=  userService.insert(userDO);
                userDOS.add(userDO);
               // userDOS.get(0) = userDO;
            }

            //第四步，根据手机号码生成自定义登录态
            String returnToken = userService.getToken(sendSmsVo.getAccount());
            //第五步，将生成的登录态和手机号码关联
            Map cache = new HashMap();
            cache.put("mobile", sendSmsVo.getAccount());

            //第六步，返回登录态和用户信息
            Map<String, Object> map = new HashMap<>();
            //20200701 pjr新增isOpenId
            if (sendSmsVo.getWxId().equals(101)) {
                if (StringUtils.isBlank(userDOS.get(0).getCerOpenId())) {
                    map.put("isOpenId", false);//没有OpenId
                } else {
                    map.put("isOpenId", true);//有OpenId
                }
            } else if (sendSmsVo.getWxId().equals(102)) {
                if (StringUtils.isBlank(userDOS.get(0).getTraOpenId())) {
                    map.put("isOpenId", false);
                } else {
                    map.put("isOpenId", true);
                }
            }
            map.put("token",returnToken);
            map.put("userId", userDOS.get(0).getId());
            map.put("userName", userDOS.get(0).getUsername());
            map.put("headPortrait", userDOS.get(0).getHeadPortrait());
            return ApiResult.success(map);
        }
    }

    private String jmMobile(String mobile) {
        mobile = mobile.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2");
        return mobile;
    }





}
